//
//  KDMessagePostController.m
//  WangJingApp
//
//  Created by 魏强 on 17/1/10.
//  Copyright © 2017年 KDTech. All rights reserved.
//  信息报送板块

#import "KDMessagePostController.h"
#import "NSDate+Extension.h"
#import "WQSeparatorView.h"
#import "SCChart.h"
#import "KDRectanglesProgress.h"
#import "KDUnitPerformanceCell.h"
#import "KDUnitPerformanceModel.h"
#import "KDManageRequestTool.h"
#define KDSuperMsgColor WQColor(251, 182, 64)
#define KDAllMsgColor WQColor(46, 183, 242)
#define KDSelfMsgColor WQColor(252, 101, 116)
@interface KDMessagePostController ()<UITableViewDelegate, UITableViewDataSource,UIScrollViewDelegate>
/**  scrollView的宽度约束 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollView_Cons_w;
/**  scrollView的高度约束 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollView_Cons_h;

@property (weak, nonatomic) IBOutlet UILabel *dateLb;

/**  想要看的那一个日期 */
@property (nonatomic, strong) NSDate * date;
/**   */
@property (nonatomic, retain) NSDateFormatter *fmt;
/**  请求时输入的日期参数 */
@property (nonatomic, copy) NSString * dateStr;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (weak, nonatomic) IBOutlet WQSeparatorView *dateView;
@property (weak, nonatomic) IBOutlet UIView *pieChartUnderView;
/**  饼状图 */
@property (nonatomic, weak) SCPieChart *chartView;
/**  采分率进度条 */
@property (weak, nonatomic) IBOutlet KDRectanglesProgress *usefulMsgProgress;
/**  本单位采分率进度条 */

/**  上级单位采分率进度条 */

@property (weak, nonatomic) IBOutlet UITableView *tableView;
/**  单位表现数据汇总 */
@property (nonatomic, strong) NSArray *infoArr;
/**  上一次的滑动位置 */
@property (nonatomic, assign) float lastContentOffset;
/**  tabBar原始y */
@property (nonatomic, assign) CGFloat originalTabY;

/**  选择是本单位还是下级单位报送 */
@property (weak, nonatomic) IBOutlet UISegmentedControl *unitChooseSegment;

/**************  得分榜板块 *****************/

/**  得分榜 */
@property (weak, nonatomic) IBOutlet UILabel *monthTopLabel;
@property (weak, nonatomic) IBOutlet UILabel *top1ScoreLb;
@property (weak, nonatomic) IBOutlet UILabel *top1AddLb;
@property (weak, nonatomic) IBOutlet UIButton *top1ScoreBtn;

@property (weak, nonatomic) IBOutlet UIButton *top2ScoreBtn;
@property (weak, nonatomic) IBOutlet UILabel *top2ScoreLb;
@property (weak, nonatomic) IBOutlet UILabel *top2AddLb;

@property (weak, nonatomic) IBOutlet UIButton *top3ScoreBtn;
@property (weak, nonatomic) IBOutlet UILabel *top3ScoreLb;
@property (weak, nonatomic) IBOutlet UILabel *top3AddLb;

/**************  总体报送情况板块 *****************/

/**  每周或每日选择器 */
@property (weak, nonatomic) IBOutlet UISegmentedControl *dateSegement;
/**  上级单位采分分数 */
@property (weak, nonatomic) IBOutlet UILabel *submissionScoreLb;
/**  上级单位采分信息条数进度条 */
@property (weak, nonatomic) IBOutlet KDRectanglesProgress *superMsgProgress;
/**  上级单位采分信息条数 */
@property (weak, nonatomic) IBOutlet UILabel *infoAcceptedLb;


/**  -本单位采分分数 */
@property (weak, nonatomic) IBOutlet UILabel *submissionScoredLb;
/**  本单位采分信息条数进度条 */
@property (weak, nonatomic) IBOutlet KDRectanglesProgress *selfMsgProgress;
/**  本单位采分信息条数 */
@property (weak, nonatomic) IBOutlet UILabel *subordinateAcceptedLb;
/**  采分率LB */
@property (weak, nonatomic) IBOutlet UILabel *acceptPercentLb;
/**  上报信息总数 */
@property (weak, nonatomic) IBOutlet UILabel *allSubmissionLb;
/**  被采信息总数 */
@property (weak, nonatomic) IBOutlet UILabel *allAcceptLb;

/**  数据模型 */
@property (nonatomic, strong) KDMessagePostData *data;

@end

@implementation KDMessagePostController
#pragma mark - 懒加载区
- (NSDateFormatter *)fmt
{
    if (!_fmt) {
        _fmt = [[NSDateFormatter alloc]init];
        _fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];;
        _fmt.dateFormat = @"yyyy.MM.dd";
    }
    return _fmt;
}
- (NSArray *)infoArr
{
    if (!_infoArr) {
        _infoArr = [[NSArray alloc]init] ;
    }
    return _infoArr;
}

- (void)setDate:(NSDate *)date{
    _date = date;
    self.dateStr = [[self.fmt stringFromDate:date] stringByReplacingOccurrencesOfString:@"." withString:@""];
}
#pragma mark - 生命周期区
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.date = [NSDate date];
    NSString *dateStr = [self.fmt stringFromDate:self.date];
    self.dateLb.text = dateStr;
    self.dateView.separatorMode = WQViewSeparatorModeTopAndBottom;
    self.dateView.separatorColor = WQColor(238, 238, 238);
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.originalTabY = self.tabBarController.tabBar.y;
    [self setupPieChartView];
    [self setupTableView];
    
    [self loadMainData];
   }
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.scrollView_Cons_w.constant = screenW;

}
#pragma mark - 板块布置区
- (void)setupTableView{
    UINib *xib = [UINib nibWithNibName:@"KDUnitPerformanceCell" bundle:nil];
    [self.tableView registerNib:xib forCellReuseIdentifier:@"KDUnitPerformanceCell"];

    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    // 设置footer
    self.tableView.footer = footer;
    [self.tableView.header beginRefreshing];
}
- (void)setupPieChartView{
    NSArray *items = @[[SCPieChartDataItem dataItemWithValue:10 color:KDAllMsgColor description:nil],
                       [SCPieChartDataItem dataItemWithValue:20 color:KDSelfMsgColor description:nil]
                       ];
    CGFloat height = self.pieChartUnderView.height;
   SCPieChart *  chartView= [[SCPieChart alloc] initWithFrame: CGRectMake((screenW - height) *0.5 , 0, height, height) items:items];
//    KDLog(@"%@", NSStringFromCGRect(chartView.frame));
    self.chartView = chartView;
    chartView.descriptionTextColor = [UIColor clearColor];
//    chartView.hasLegend = YES;
    chartView.descriptionTextFont  = [UIFont fontWithName:@"Avenir-Medium" size:9.0];
//    self.chartView.showAbsoluteValues = YES;
    [chartView strokeChart];
    [self.pieChartUnderView addSubview:chartView];
    
}
- (void)setupPersentage{
    self.usefulMsgProgress.color = KDSelfMsgColor;
    self.selfMsgProgress.color = KDAllMsgColor;
    self.superMsgProgress.color = KDSuperMsgColor;
    self.selfMsgProgress.showPersentageLb = NO;
    self.usefulMsgProgress.showPersentageLb = NO;
    self.superMsgProgress.showPersentageLb = NO;


    KDEveryOrWeekModel * everyOrWeek= self.data.everyOrWeek;
    
    self.usefulMsgProgress.persentage = everyOrWeek.acceptPercent/100;

    if (!everyOrWeek.allAccept.floatValue || !everyOrWeek.allSubmission.floatValue) {//全是空
        self.selfMsgProgress.persentage = 0;
        self.superMsgProgress.persentage = 0;
    }else{
        self.selfMsgProgress.persentage = everyOrWeek.subordinateAccepted/everyOrWeek.allAccept.floatValue;
        
        self.superMsgProgress.persentage = everyOrWeek.infoAccepted/everyOrWeek.allAccept.floatValue;
    }
    
}
#pragma mark - 事件点击区
- (IBAction)dateBtnClick:(UIButton *)sender {
    if (sender.tag == 1) {
        self.date = [self.date yesterday];
    }else{
        self.date = [self.date tomorrow];
    }
   
    NSString *dateStr = [self.fmt stringFromDate:self.date];
    self.dateLb.text = dateStr;
    [self loadMainData];
    
}
/**
 *  本单位还是下级单位报送的
 */
- (IBAction)unitSegmentClick:(UISegmentedControl *)sender {
    [self loadMainData];
}
/**  每周还是每日的选择器被点击了 */
- (IBAction)dayOrWeekSegmentClick:(id)sender {
    [self loadMainData];
}

- (void)changePieChartView{
    KDEveryOrWeekModel *everyOrWeek =self.data.everyOrWeek;
    KDLog(@"%f",everyOrWeek.acceptPercent);
    NSArray *ary = @[[NSString stringWithFormat:@"%f",(100-everyOrWeek.acceptPercent)],[NSString stringWithFormat:@"%f",everyOrWeek.acceptPercent]];
    
//    for (NSInteger i = 0; i < 3; i++) {
//        CGFloat num = arc4random_uniform(100);
//        NSString *str = [NSString stringWithFormat:@"%f",num];
//        [ary addObject:str];
//    }
    [self.chartView updateChartByNumbers:ary];
}

#pragma mark - 网络请求区
/**  主要的网络请求 */
- (void)loadMainData{
    KDMessegePostParam *param = [[KDMessegePostParam alloc]init];
    param.method = @"calendar/unitInfoSubmission";
    param.myUnit = !self.unitChooseSegment.selectedSegmentIndex;
    param.isDay = !self.dateSegement.selectedSegmentIndex;
    param.snapDate = self.dateStr;
    [KDManageRequestTool getMessegePostWithParam:param success:^(KDMessegePostResult *responseObejct) {
        if ([responseObejct.status isEqualToString:@"1"]) {
            self.data = responseObejct.data;
            
            self.data.everyOrWeek.selfSubmission = !self.unitChooseSegment.selectedSegmentIndex;
            [self reloadData];
            KDLog(@"2333333333333");
        }
    } failure:^(NSError *error) {
        KDLog(@"%@", error);
    }];
}
/**
 *  更新得分榜板块
 */
- (void)reloadTopScore{
    KDSubmissionUnit *unit2;
    KDSubmissionUnit *unit3;
    KDSubmissionUnit *unit1;
    //1.1判断合集是否存在
    if (self.data.subScoreTop.count) {
        unit1 = self.data.subScoreTop[0];
        unit1.fullDesc = [NSString stringWithFormat:@"NO.1\n%ld条",unit1.mark];
        //        self.top1ScoreLb.text = [NSString stringWithFormat:@"NO.1\n%ld条",unit1.mark];
        //        self.top1AddLb.text = unit1.check_desc;
        //存在的话就判断有几个
        if (self.data.subScoreTop.count == 2) {
            unit2 = self.data.subScoreTop[1];
            unit2.fullDesc = [NSString stringWithFormat:@"NO.2\n%ld条",unit2.mark];
            unit3 = [[KDSubmissionUnit alloc]init];
            unit3.fullDesc = @"无";
        }else{
            unit2 = self.data.subScoreTop[1];
            unit2.fullDesc = [NSString stringWithFormat:@"NO.2\n%ld条",unit2.mark];
            unit3 = self.data.subScoreTop[2];
            unit3.fullDesc = [NSString stringWithFormat:@"NO.3\n%ld条",unit3.mark];
        }
    }else{
        unit1 = [[KDSubmissionUnit alloc]init];
        unit1.fullDesc = @"无";
        unit2 = [[KDSubmissionUnit alloc]init];
        unit2.fullDesc = @"无";
        unit3 = [[KDSubmissionUnit alloc]init];
        unit3.fullDesc = @"无";
    }
    
    self.top1ScoreLb.text = unit1.fullDesc;
    self.top1AddLb.text = unit1.check_desc;
    self.top1ScoreBtn.selected = (!unit1.check_desc);
    
    self.top2ScoreLb.text = unit2.fullDesc;
    self.top2AddLb.text = unit2.check_desc;
    self.top2ScoreBtn.selected = (!unit2.check_desc);
    
    self.top3ScoreLb.text = unit3.fullDesc;
    self.top3AddLb.text = unit3.check_desc;
    self.top3ScoreBtn.selected = (!unit3.check_desc);
}
/**
 *  更新报送情况板块
 */
- (void)reloadAllSubmission{
    KDEveryOrWeekModel *everyOrWeek = self.data.everyOrWeek;
    self.allSubmissionLb.text = everyOrWeek.allSubmission;
    self.allAcceptLb.text = everyOrWeek.allAccept;
    self.acceptPercentLb.text = [NSString stringWithFormat:@"%.1f%%", everyOrWeek.acceptPercent];
    self.subordinateAcceptedLb.text = [NSString stringWithFormat:@"%ld", everyOrWeek.subordinateAccepted];
    
    self.infoAcceptedLb.text = [NSString stringWithFormat:@"%ld", everyOrWeek.infoAccepted];
    
    self.submissionScoredLb.text = [NSString stringWithFormat:@"%ld", everyOrWeek.submissionScored];
    self.submissionScoreLb.text = [NSString stringWithFormat:@"%ld", everyOrWeek.submissionScore];
    
    [self changePieChartView];
    [self setupPersentage];
}
- (void)reloadData{
    //1.0 得分榜
    [self reloadTopScore];
    
    //2.报送情况板块
    [self reloadAllSubmission];
    

}
- (void)loadData{
    self.infoArr = [self getFakeData];
    [self.tableView reloadData];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView.header endRefreshing];
    });
}
- (void)loadMoreData{
    //    self.page.integerValue ++;
    NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
    [arr addObjectsFromArray:[self getFakeData]] ;
    self.infoArr = arr;
    [self.tableView reloadData];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView.footer endRefreshing];
    });
    
}
- (NSArray *)getFakeData
{
    
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"FakeUnitPerformance" ofType:@"plist"];
    
    //    NSArray *data = [[NSArray alloc] initWithContentsOfFile:plistPath];
    return [KDUnitPerformanceModel objectArrayWithFile:plistPath];
    
}

#pragma mark - 通知接收区

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return self.infoArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KDUnitPerformanceCell *cell = [KDUnitPerformanceCell cellWithTableView:tableView];
        if (self.infoArr.count != 0) {
            cell.model = self.infoArr[indexPath.row];
        }
        return cell;

}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == self.scrollView) {
         self.lastContentOffset = scrollView.contentOffset.y;
    }
   
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView == self.scrollView) {
        NSInteger yOffset = scrollView.contentOffset.y;
        UITabBar *tb = self.tabBarController.tabBar;
        if (yOffset > 0) {//视情况隐藏tabar
            [UIView animateWithDuration:0.5 animations:^{
                tb.y = self.originalTabY + yOffset;
            }];
        }
        if (yOffset < self.lastContentOffset) {
            [UIView animateWithDuration:0.5 animations:^{
                tb.y = self.originalTabY;
            }];
        }
    }
    
}
@end
